﻿
using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Collections.Generic;
using System.Xml;

namespace SimpleService.Config
{
    public class ConfigHelper
    {
        private string _fileName = "";
        private string _directory = "";
        private List<Config> _listConfigs = new List<Config>();
        private XmlDocument doc = new System.Xml.XmlDocument();
        private XmlNodeList nodeList;
        private XmlNode node;
        private XmlElement elem;
        private XmlText text;

        /// <summary>
        /// 設定config檔名
        /// </summary>
        public string fileName
        {
            get
            {
                return _fileName;
            }
            set
            {
                _fileName = ConfigUtility.GetPath(directory + "/" + value + ".config");
            }
        }

        /// <summary>
        /// 設定config所在目錄
        /// </summary>
        public string directory
        {
            get
            {
                if (_directory == "")
                {
                    _directory = "config";
                }
                return _directory;
            }
            set
            {
                _directory = value;
            }

        }


        private void LoadConfings()
        {            
            doc.Load(fileName);
            
            node = doc.DocumentElement;
            nodeList = node.SelectNodes("/configs/config");
            foreach (XmlNode myNode in nodeList)
            {
                string id = myNode.Attributes["id"].Value;
                string value = myNode.LastChild.InnerText.Trim();

                Config con = new Config();
                con.Id = id;
                con.Value = value;
                _listConfigs.Add(con);
            }
        }

        /// <summary>
        /// 取得config資料
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Get(string str)
        {
            while (_listConfigs.Count <= 0)
            { // 還沒讀 config 先去 Load
                LoadConfings();
            }
            try
            {
                return _listConfigs.Find(
                       delegate(Config config).
                       {
                           return config.Id == str;
                       }).Value;
            }
            catch
            {
                throw new Exception(" [ SettingError：Can't find config ]");
            }
        }


        /// <summary>
        /// 寫入config資料
        /// </summary>
        /// <param name="setId"></param>
        /// <param name="setStr"></param>
        public void Set(string setId, string setVal)
        {                                           
            doc.Load(fileName);
                        
            if (isExists(doc, setId)) //如果存在
            {
                nodeList = doc.SelectSingleNode("/configs").ChildNodes;
                foreach (XmlNode mynode in nodeList)
                {
                    elem = (XmlElement)mynode;
                    if (elem.GetAttribute("id") == setId)
                    {
                        if (elem.InnerText == setVal)
                        {
                            break;
                        }
                        else
                        {
                            elem.InnerText = setVal;
                            doc.Save(fileName);
                            break;
                        }
                    }
                }   
            }
            else
            {
                node = doc.SelectSingleNode("/configs");
                elem = doc.CreateElement("config");
                elem.SetAttribute("id", setId);
                text = doc.CreateTextNode(setVal);
                elem.AppendChild(text);
                node.AppendChild(elem);
                doc.Save(fileName);
            }
            
        }

        /// <summary>
        /// 產生設定檔
        /// </summary>        
        public void Creat()
        {            
            ConfigUtility.CreateDirectory(directory);

            if ( fileName != "" && !File.Exists(fileName))
            {
                XmlDocument xmlDoc = new XmlDocument();

                XmlNode node = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
                xmlDoc.AppendChild(node);

                elem = xmlDoc.CreateElement("", "configs", ""); //加入一個根元素
                xmlDoc.AppendChild(elem);
                xmlDoc.Save(fileName);
            }
        }

        /// <summary>
        /// 移除config資料
        /// </summary>
        /// <param name="setId"></param>
        public void Remove(string setId)
        {                      
            doc.Load(fileName);
            if (isExists(doc, setId)) //如果存在
            {
                nodeList = doc.SelectSingleNode("/configs").ChildNodes;
                node = doc.SelectSingleNode("//configs");
                foreach (XmlNode mynode in nodeList)
                {
                    elem = (XmlElement)mynode;
                    if (elem.GetAttribute("id") == setId)
                    {                        
                        node.RemoveChild(elem);
                        doc.Save(fileName);
                        break;
                    }
                }
            }           
        }


        /// <summary>
        /// 判斷config中是否存在 指定id
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="setId"></param>
        /// <returns></returns>
        private bool isExists(XmlDocument doc, string setId)
        {            
            bool isExists = false;
            node = doc.SelectSingleNode("/configs/config [@id='" + setId + "']");
            if (node != null)
            {
                isExists = true;
            }
            return isExists;
        }

    }
}

